package com.icesoft.core.web.suppose.param;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

import com.icesoft.core.web.suppose.param.IValueEnum;

import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;

public class StringToEnumConverterFactory implements ConverterFactory<String, IValueEnum> {

	@SuppressWarnings("rawtypes")
	private static final Map<Class, Converter> converterMap = new WeakHashMap<>();

	private static Object lock = new Object();

	@Override
	public <T extends IValueEnum> Converter<String, T> getConverter(Class<T> targetType) {
		@SuppressWarnings("unchecked")
		Converter<String, T> converter = converterMap.get(targetType);
		if (converter == null) {
			synchronized (lock) {
				if (converterMap.get(targetType) == null) {
					converter = new StringToEnumConverter<>(targetType);
					converterMap.put(targetType, converter);
				}
			}
		}
		return converter;
	}

	class StringToEnumConverter<T extends IValueEnum> implements Converter<String, T> {

		private Map<String, T> enumMap = new HashMap<>();

		StringToEnumConverter(Class<T> enumType) {
			T[] enums = enumType.getEnumConstants();
			for (T e : enums) {
				enumMap.put(e.getValue(), e);
			}
		}

		@Override
		public T convert(String source) {

			T t = enumMap.get(source);
			if (t == null) {
				// 异常可以稍后去捕获
				throw new IllegalArgumentException("No element matches " + source);
			}
			return t;
		}
	}
}
